#include "cacherebuildmanager.h"
#include "customfilebrowser.h"
#include "mainwindow.h"
#include <QDebug>
#include <QTimer>

CacheRebuildManager::CacheRebuildManager(QObject* parent)
    : QObject(parent)
    , m_delayTimer(new QTimer(this))
{
    // 设置延迟执行定时器
    m_delayTimer->setSingleShot(true);
    connect(m_delayTimer, &QTimer::timeout, this, &CacheRebuildManager::delayedRebuild);
}

bool CacheRebuildManager::analyzeConfigChange(const SystemConfig& oldConfig,
                                            const SystemConfig& newConfig)
{
    m_oldConfig = oldConfig;
    m_newConfig = newConfig;

    bool dpiChanged = (oldConfig.processingQuality != newConfig.processingQuality);
    bool cacheDirChanged = (oldConfig.cacheDirectory != newConfig.cacheDirectory);

    if (dpiChanged || cacheDirChanged) {

        // 生成Toast提示
        QString message = generateRebuildMessage(oldConfig, newConfig);
        emit rebuildProgress(message);

        return true;
    }

    return false;
}

void CacheRebuildManager::executeCacheRebuild()
{

    // 延迟执行，避免阻塞配置对话框的关闭
    m_delayTimer->start(REBUILD_DELAY_MS);
}

void CacheRebuildManager::setFileList(const QList<UnifiedFileInfo>& files)
{
    m_files = files;
}

void CacheRebuildManager::setCurrentFilePath(const QString& filePath)
{
    m_currentFilePath = filePath;
}

void CacheRebuildManager::delayedRebuild()
{

    // 通过信号通知MainWindow执行实际的重建
    // 这样保持了职责分离：CacheRebuildManager负责决策，MainWindow负责执行
    emit rebuildCompleted();
}

bool CacheRebuildManager::isDPIOnlyChange(const SystemConfig& oldConfig,
                                         const SystemConfig& newConfig)
{
    return (oldConfig.processingQuality != newConfig.processingQuality) &&
           (oldConfig.cacheDirectory == newConfig.cacheDirectory);
}

bool CacheRebuildManager::isCacheDirectoryChanged(const SystemConfig& oldConfig,
                                                 const SystemConfig& newConfig)
{
    return oldConfig.cacheDirectory != newConfig.cacheDirectory;
}

QString CacheRebuildManager::generateRebuildMessage(const SystemConfig& oldConfig,
                                                   const SystemConfig& newConfig)
{
    QStringList changes;

    if (oldConfig.processingQuality != newConfig.processingQuality) {
        // 简化DPI提示，更简洁
        changes << "DPI已更新";
    }

    if (oldConfig.cacheDirectory != newConfig.cacheDirectory) {
        changes << "缓存目录已更换";
    }

    if (changes.isEmpty()) {
        return QString();
    }

    // 简化提示文案
    return QString("正在更新缓存：%1").arg(changes.join("，"));
}